package okhttp3.internal.platform.ohos;

import okhttp3.Protocol;
import okhttp3.internal.platform.ConscryptPlatform;
import org.conscrypt.Conscrypt;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.util.List;

import static okhttp3.internal.platform.Platform.alpnProtocolNames;

public class ConscryptSocketAdapter implements SocketAdapter {
    private static final DeferredSocketAdapter.Factory factory = (DeferredSocketAdapter.Factory) (new DeferredSocketAdapter.Factory() {
        public Boolean matchesSocket(SSLSocket sslSocket) {
            boolean isTrue = false;
            if (null != ConscryptPlatform.buildIfSupported()) {
                isTrue = true;
            }
            return isTrue && Conscrypt.isConscrypt(sslSocket);
        }

        public SocketAdapter create(SSLSocket sslSocket) {
            return (SocketAdapter) (new ConscryptSocketAdapter());
        }
    });

    @Override
    public Boolean isSupported() {
        boolean isTrue = false;
        if (null != ConscryptPlatform.buildIfSupported()) {
            isTrue = true;
        }
        return isTrue;
    }

    @Override
    public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
        return null;
    }

    @Override
    public Boolean matchesSocket(SSLSocket sslSocket) {
        return Conscrypt.isConscrypt(sslSocket);
    }

    @Override
    public Boolean matchesSocketFactory(SSLSocketFactory sslSocketFactory) {
        return null;
    }

    @Override
    public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
        if (this.matchesSocket(sslSocket)) {
            Conscrypt.setUseSessionTickets(sslSocket, true);
            List names = alpnProtocolNames(protocols);
            Object[] objects = new Object[names.size()];
            names.toArray(objects);
            Conscrypt.setApplicationProtocols(sslSocket, (String[]) objects);
        }
    }

    @Override
    public String getSelectedProtocol(SSLSocket sslSocket) {
        return this.matchesSocket(sslSocket) ? Conscrypt.getApplicationProtocol(sslSocket) : null;
    }

    class Companion {
        public final DeferredSocketAdapter.Factory getFactory() {
            return ConscryptSocketAdapter.factory;
        }

        public SocketAdapter create(SSLSocket sslSocket) {
            return ConscryptSocketAdapter.this;
        }

        private Companion() {
        }
    }
}
